﻿using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public class DragAdorner : Adorner
    {
        protected UIElement Child;
        protected UIElement Owner;
        protected double XCenter;
        protected double YCenter;
        private double _leftOffset;
        private double _topOffset;
        public double Scale = 1.0;

        public DragAdorner(UIElement owner) : base(owner) { }
        public DragAdorner(UIElement owner, UIElement adornElement, double opacity) : base(owner)
        {
            Owner = owner;
            VisualBrush brush = new VisualBrush(adornElement)
            {
                Opacity = opacity
            };
            Rectangle r = new Rectangle
            {
                RadiusX = 3,
                RadiusY = 3,
                Width = adornElement.DesiredSize.Width,
                Height = adornElement.DesiredSize.Height
            };
            XCenter = adornElement.DesiredSize.Width / 2;
            YCenter = adornElement.DesiredSize.Height / 2;
            r.Fill = brush;
            Child = r;
        }

        public double LeftOffset
        {
            get => _leftOffset;
            set
            {
                _leftOffset = value - XCenter;
                UpdatePosition();
            }
        }

        public double TopOffset
        {
            get => _topOffset;
            set
            {
                _topOffset = value - YCenter;
                UpdatePosition();
            }
        }

        protected override int VisualChildrenCount => 1;

        private void UpdatePosition()
        {
            AdornerLayer adorner = (AdornerLayer)Parent;
            adorner?.Update(AdornedElement);
        }

        protected override Visual GetVisualChild(int index)
        {
            return Child;
        }

        protected override Size MeasureOverride(Size finalSize)
        {
            Child.Measure(finalSize);
            return Child.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            Child.Arrange(new Rect(Child.DesiredSize));
            return finalSize;
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            GeneralTransformGroup result = new GeneralTransformGroup();
            result.Children.Add(base.GetDesiredTransform(transform));
            result.Children.Add(new TranslateTransform(_leftOffset, _topOffset));
            return result;
        }
    }
}
